<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import {
  getCurrentLoginUserState,
  setCurrentLoginUserState,
} from "@/state/userState";
import { getCurrentUser, updateUser } from "@/services/userService";
import { ref } from "vue";
import { showToast } from "vant";

const route = useRoute();
const router = useRouter();
let { value, key, property } = route.query;
let reactiveValue = ref(value);
const onSubmit = async () => {
  const user = await getCurrentLoginUserState();
  const { data: res } = await updateUser(
    user.id,
    property,
    reactiveValue.value,
  );
  if (res === 1) {
    const data = await getCurrentUser();
    const { message, description, data: newUser } = data;
    setCurrentLoginUserState(newUser);
    router.back();
    showToast("更新成功");
  } else {
    showToast(description.length ? description : message);
  }
};
</script>

<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="reactiveValue"
        :label="key"
        :rules="[{ required: true, message: `请填写${key}` }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<style scoped></style>
